package com.hongyi.common.framework.utils.common;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;

import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;

/**
 * IO工具类<br>
 * IO工具类只是辅助流的读写，并不负责关闭流。原因是流可能被多次读写，读写关闭后容易造成问题。
 *
 * @author DingHao
 */
public class IoUtils {

    public static final int DEFAULT_BUFFER_SIZE = 2 << 12;

    /**
     * 从Reader中读取String，读取完毕后关闭Reader
     *
     * @param reader Reader
     * @return String
     * @throws IORuntimeException IO异常
     */
    public static String read(Reader reader) throws IORuntimeException {
        return read(reader, true);
    }

    /**
     * 从{@link Reader}中读取String
     *
     * @param reader  {@link Reader}
     * @param isClose 是否关闭{@link Reader}
     * @return String
     * @throws IORuntimeException IO异常
     */
    public static String read(Reader reader, boolean isClose) throws IORuntimeException {
        final StringBuilder builder = StrUtil.builder();
        final CharBuffer buffer = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
        try {
            while (-1 != reader.read(buffer)) {
                builder.append(buffer.flip());
            }
        } catch (IOException e) {
            throw new IORuntimeException(e);
        } finally {
            if (isClose) {
                IoUtil.close(reader);
            }
        }
        return builder.toString();
    }

}
